<template>
  <div>
    <span>单文件上传</span>
    <input type="file" name="" value="" @change="fileChange" />
  </div>
  <div>
    <span>多文件上传</span>
    <input type="file" name="" value="" @change="filesChange" multiple />
  </div>
  <img ref="imgRef" :src="base64Url" alt="" />
</template>

<script setup>
/**
 * 对图片压缩的步骤：
 * 1. 用 canvas 的 drawImage 绘制图片
 * 2. 转化成 toBlob 或者 toDataURL, 然后压缩
 */
import { ref, nextTick } from "vue";
import { saveAs } from "file-saver";
import axios from "axios";

let base64Url = ref("");
let imgRef = ref(null);
let host = "/api";
// 单文件
const fileChange = (e) => {
  let file = e.target.files[0];
  let fr = new FileReader();
  fr.readAsDataURL(file);
  fr.onload = function () {
    base64Url.value = fr.result;
    // 保证获取到图片以后再对其进行操作 nextTick
    nextTick(() => {
      // 创建 canvas标签
      let pressCanvas = document.createElement("canvas");
      // 获取canvas标签的宽高
      pressCanvas.width = imgRef.value.width;
      pressCanvas.height = imgRef.value.height;
      // 创建 canvas 的 二维画布
      let ctx = pressCanvas.getContext("2d");
      // drawImage 方法绘制图片 5个参数：1.图片的具体DOM元素 2.x轴从哪儿开始画 3.y轴从哪儿开始画 4.画多宽 5.画多高
      ctx.drawImage(
        imgRef.value,
        0,
        0,
        imgRef.value.width,
        imgRef.value.height
      );
      // 用canvas标签来压缩成  toBlob 或者 toDataURL
      // toBlob三个参数：1.压缩后的blob回调函数 2.压缩后的图片类型 3.压缩大小 范围是 0-1
      pressCanvas.toBlob(
        (blob) => {
          // 下载图片
          //  saveAs(blob, 'a')
          // 上传图片
          uploadFile(file, "/upload-single", "file");
        },
        "image/jpeg",
        0.6
      );
    });
  };
};

// 封装文件上传
const uploadFile = (file, url, fileName) => {
  let _formData = new FormData();
  _formData.append(fileName, file);
  axios.post(host + url, _formData).then((res) => {
  });
};

// 多文件
const filesChange = (e) => {
  const files = e.target.files;
  for (let i = 0; i < files.length; i++) {
    uploadFile(files[i], "/upload-multiple", "files");
  }
};
</script>

<style lang="less" scoped></style>
